// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
var app = angular.module('starter', ['ionic', 'oc.lazyLoad'])

.run(function($ionicPlatform, $rootScope,$state,$ionicPopup,$timeout,$ionicLoading,$ionicHistory,LoginService) {
	$rootScope.goPrevView = function(){
		$ionicHistory.goBack();
	}
	//返回键处理
	/*$ionicPlatform.registerBackButtonAction(function (e) {
	    e.preventDefault();
	    //alert(12345);
	    return false;
	}, 101);*/
	
	$ionicPlatform.ready(function() {
		//判断用户是否登录
		teamLog("run:"+localStorage.haslogin)
	    if(localStorage.haslogin != 0){
	    	$ionicLoading.show({template: "登录信息过期，请重新登录", noBackdrop: true, duration: 2000});
	  		$state.go('login');
	    }
		//LoginService.islive();
		//需要验证是否有登录的用户
		var loginTabState = ['tab.me'];
		//监听路由事件 
		$rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams) {
	 		if(loginTabState.indexOf(toState.name) >= 0 && localStorage.haslogin != 0) {
	 			event.preventDefault();
	 			$ionicPopup.alert({
					title: "提示",
					template: "请先登陆！",
					okText: "知道了"
				}).then(function() {
					$state.go("login");
				});
	 		}
	 	});
	    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
	    // for form inputs)
	    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
		    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
		    cordova.plugins.Keyboard.disableScroll(true);
		    //隐藏启动页面
			setTimeout(function () {  
		       navigator.splashscreen.hide();  
		    }, 1000); 
	    }
	    if (window.StatusBar) {
	        // org.apache.cordova.statusbar required
	        StatusBar.styleDefault();
	    }
	    
	    //判断网络状态
	    document.addEventListener("deviceready", function() {
			var networkState = navigator.connection.type;
			var states = {};
			//网络状态  
			states[Connection.UNKNOWN] = 'Unknown connection';
			states[Connection.ETHERNET] = 'Ethernet connection';
			states[Connection.WIFI] = 'WiFi connection';
			states[Connection.CELL_2G] = 'Cell 2G connection';
			states[Connection.CELL_3G] = 'Cell 3G connection';
			states[Connection.CELL_4G] = 'Cell 4G connection';
			states[Connection.CELL] = 'Cell generic connection';
			states[Connection.NONE] = '网络异常，不能连接到服务器';
		
			if(states[networkState] == "网络异常，不能连接到服务器") {
				$ionicLoading.show({
					template: states[networkState]
				});
			} else {
				$ionicLoading.show({
					template: states[networkState]
				});
			}
			teamLog(states[networkState]);
		}, false);
	});
})

.config(['$stateProvider', '$ionicConfigProvider','$urlRouterProvider', 
         '$controllerProvider', '$compileProvider', '$filterProvider', 
         '$provide', '$ocLazyLoadProvider', 'JS_REQUIRES',
         '$httpProvider',
function($stateProvider ,  $ionicConfigProvider,  $urlRouterProvider,    
	     $controllerProvider,  $compileProvider,    $filterProvider,   
	     $provide,   $ocLazyLoadProvider,   jsRequires,
		 $httpProvider
        ) {
	app.controller = $controllerProvider.register;
	app.directive = $compileProvider.directive;
	app.filter = $filterProvider.register;
	app.factory = $provide.factory;
	app.service = $provide.service;
	app.constant = $provide.constant;
	app.value = $provide.value;
  
    $ionicConfigProvider.platform.android.tabs.position('bottom');
    $ionicConfigProvider.platform.android.tabs.style('standard');
  	$ionicConfigProvider.platform.ios.backButton.previousTitleText('').icon('ion-ios-arrow-thin-left');
	$ionicConfigProvider.platform.android.backButton.previousTitleText('').icon('ion-android-arrow-back');
	/*$ionicConfigProvider.platform.ios.views.transition('ios');
	$ionicConfigProvider.platform.android.views.transition('android');*/
	
	/*$ionicConfigProvider.platform.ios.tabs.style('standard');
	$ionicConfigProvider.platform.ios.tabs.position('bottom');
	$ionicConfigProvider.platform.android.tabs.style('standard');
	$ionicConfigProvider.platform.android.tabs.position('standard');
	$ionicConfigProvider.platform.ios.navBar.alignTitle('center');
	$ionicConfigProvider.platform.android.navBar.alignTitle('left');
	$ionicConfigProvider.platform.ios.backButton.previousTitleText('').icon('ion-ios-arrow-thin-left');
	$ionicConfigProvider.platform.android.backButton.previousTitleText('').icon('ion-android-arrow-back');
	$ionicConfigProvider.platform.ios.views.transition('ios');
	$ionicConfigProvider.platform.android.views.transition('android');*/

	/*******************************************
	  说明：$http的post提交时，纠正消息体
	********************************************/
	// Use x-www-form-urlencoded Content-Type
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
	//$http.defaults.headers.common.Authorization = 'Bearer ' + token;
	$httpProvider.defaults.headers.common.Authorization = 'Bearer ' + localStorage.ticken;
	
	
	 /*
	  * The workhorse; converts an object to x-www-form-urlencoded serialization.
	  * @param {Object} obj
	  * @return {String}
	  */
	var param = function(obj) {
	 	var query = '',
	 		name, value, fullSubName, subName, subValue, innerObj, i;
	 	for(name in obj) {
	 		value = obj[name];
	 		if(value instanceof Array) {
	 			for(i = 0; i < value.length; ++i) {
	 				subValue = value[i];
	 				fullSubName = name + '[' + i + ']';
	 				innerObj = {};
	 				innerObj[fullSubName] = subValue;
	 				query += param(innerObj) + '&';
	 			}
	 		} else if(value instanceof Object) {
	 			for(subName in value) {
	 				subValue = value[subName];
	 				fullSubName = name + '[' + subName + ']';
	 				innerObj = {};
	 				innerObj[fullSubName] = subValue;
	 				query += param(innerObj) + '&';
	 			}
	 		} else if(value !== undefined && value !== null)
	 			query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
	 	}
	 	return query.length ? query.substr(0, query.length - 1) : query;
	};
	// Override $http service's default transformRequest
	$httpProvider.defaults.transformRequest = [
	 	function(data) {
	 		return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
	 	}
	];


    // Ionic uses AngularUI Router which uses the concept of states
    // Learn more here: https://github.com/angular-ui/ui-router
    // Set up the various states which the app can be in.
    // Each state's controller can be found in controllers.js
$stateProvider
    .state('login',{url:'/login',templateUrl: 'templates/login.html' ,controller: 'LoginCtrl',resolve: loadSequence('LoginArgs') })
    // setup an abstract state for the tabs directive
    .state('tab', {url: '/tab', abstract: true, templateUrl: 'templates/tabs.html'  })

	// Each tab has its own nav history stack:
    .state('tab.home',  {url: '/home',views: {'tab-home': {templateUrl: 'templates/tab-home.html',controller: 'HomeCtrl',resolve: loadSequence('HomeArgs') }}}) 
  		//个人中心
	    .state('tab.center',  {url: '/home/center', views: {'tab-home': {templateUrl: 'page/home/home-center.html', controller: 'HomeCenterCtrl' ,resolve: loadSequence('HomeCenterCtrl') }}})
	    //包裹集市
	    .state('tab.home-bg', {url: '/home/home-bg',views: {'tab-home': {templateUrl: 'page/home/home-bg/welcome.html',     controller: 'BGWelcomeCtrl'     ,resolve: loadSequence('BGWelcomeArgs') }}})
	    	.state('tab.bg-list', {url: '/home/bg-list',views: {'tab-home': {templateUrl: 'page/home/home-bg/list.html',     controller: 'BGListCtrl'     ,resolve: loadSequence('BGListArgs') }}})
	    	.state('tab.bg-detail', {url: '/home/home-bg/:listId',views: {'tab-home': {templateUrl: 'page/home/home-bg/detail.html',     controller: 'BGDetailCtrl'     ,resolve: loadSequence('BGDetailCtrlArgs') }}})
	    	.state('tab.bg-toBuy', {url: '/home/bg-toBuy',views: {'tab-home': {templateUrl: 'page/home/home-bg/toBuy.html' }}})
	    	.state('tab.bg-publish', {url: '/home/bg-publish/:listId',views: {'tab-home': {templateUrl: 'page/home/home-bg/publish.html',     controller: 'BGPublishCtrl'     ,resolve: loadSequence('BGPublishCtrl') }}})
	    	.state('tab.bg-ordination', {url: '/home/bg-ordination',views: {'tab-home': {templateUrl: 'page/home/home-bg/ordination.html' }}})
	    //股海领航
	    .state('tab.home-lh', {url: '/home/home-lh',views: {'tab-home': {templateUrl: 'page/home/home-lh/welcome.html',     controller: 'LHWelcomeCtrl'     ,resolve: loadSequence('LHWelcomeCtrlArgs') }}})
	    	.state('tab.lh-publish', {url: '/home/lh-publish',views: {'tab-home': {templateUrl: 'page/home/home-lh/publish.html',     controller: 'LHPublishCtrl'     ,resolve: loadSequence('LHPublishArgs') }}})
	    	.state('tab.lh-list', {url: '/home/lh-list',views: {'tab-home': {templateUrl: 'page/home/home-lh/list.html',     controller: 'LHListCtrl'     ,resolve: loadSequence('LHCtrlArgs') }}})
			.state('tab.lh-detail', {url: 'home/home-lh/:listId',views: {'tab-home': {templateUrl: 'page/home/home-lh/detail.html',     controller: 'LHDetailCtrl'     ,resolve: loadSequence('LHDetailCtrlArgs') }}})
		
		.state('tab.home-qn', {url: '/home/home-qn',views: {'tab-home': {templateUrl: 'page/home/home-qn/welcome.html',     controller: 'HomeqnCtrl'     ,resolve: loadSequence('HomeCenterCtrl') }}})
		.state('tab.home-hh', {url: '/home/home-hh',views: {'tab-home': {templateUrl: 'page/home/home-hh/welcome.html',     controller: 'HomehhCtrl'     ,resolve: loadSequence('HomeCenterCtrl') }}})
		//挑管家
		.state('tab.home-tg', {url: '/home/home-tg',views: {'tab-home': {templateUrl: 'page/home/home-tg/welcome.html',     controller: 'GJWelcomeCtrl'     ,resolve: loadSequence('GJWelcomeCtrl') }}})
			.state('tab.tg-list', {url: '/home/tg-list',views: {'tab-home': {templateUrl: 'page/home/home-tg/list.html',     controller: 'GJListCtrl'     ,resolve: loadSequence('GJListCtrl') }}})
			.state('tab.tg-detail', {url: '/home/tg-detail/:listId',views: {'tab-home': {templateUrl: 'page/home/home-tg/detail.html',    controller: 'GJListCtrl'     ,resolve: loadSequence('GJListCtrl') }}})
			.state('tab.tg-publish', {url: '/home/tg-publish',views: {'tab-home': {templateUrl: 'page/home/home-tg/publish.html',    controller: 'GJPublishCtrl'     ,resolve: loadSequence('GJPublishCtrl') }}})
			.state('tab.tg-bidding', {url: '/home/tg-bidding',views: {'tab-home': {templateUrl: 'page/home/home-tg/bidding.html',    controller: 'GJBiddingCtrl'     ,resolve: loadSequence('GJBiddingCtrl') }}})
			.state('tab.tg-warrant', {url: '/home/tg-warrant',views: {'tab-home': {templateUrl: 'page/home/home-tg/warrant.html',    controller: 'GJWarrantCtrl'     ,resolve: loadSequence('GJWarrantCtrl') }}})
			
		.state('tab.home-lw', {url: '/home/home-lw',views: {'tab-home': {templateUrl: 'page/home/home-lw/welcome.html',     controller: 'LWWelcomeCtrl'     ,resolve: loadSequence('LWWelcomeArgs') }}})
			.state('tab.lw-publish', {url: '/home/lw-publish',views: {'tab-home': {templateUrl: 'page/home/home-lw/publish.html',    controller: 'LWPublishCtrl'     ,resolve: loadSequence('LWPublishCtrl') }}})
			
    .state('tab.chats', {url: '/chats',views: {'tab-chats': {templateUrl: 'templates/tab-chats.html',controller: 'ChatsCtrl' ,resolve: loadSequence('ChatsArgs') }}})
    //消息下面的页面
  	.state('tab.chat-detail', {url: '/chats/:chatId',views: {'tab-chats': {templateUrl: 'page/chats/chat-detail.html',controller: 'ChatDetailCtrl' ,resolve: loadSequence('ChatDetailCtrlArgs') }}})

    .state('tab.work', {url: '/work',views: {'tab-work': {templateUrl: 'templates/tab-work.html',controller: 'WorkCtrl' ,resolve: loadSequence('WorkCtrl') }}})

    .state('tab.me', {url: '/me',views: {'tab-me': {templateUrl: 'templates/tab-me.html',controller: 'MeCtrl' ,resolve: loadSequence('MeCtrl') }}});
  
    // if none of the above states are matched, use this as the fallback
    teamLog("config:"+localStorage.haslogin)
    if(localStorage.haslogin == 0){
  		$urlRouterProvider.otherwise('/tab/home');
    }else{
  		$urlRouterProvider.otherwise('/login');
    }
  

	function loadSequence() {
		var _args = arguments;
		var viewArgs = repeatArgs(_args[0]);
		//先匹配模块的，没有再匹配单文件的
		if(viewArgs) {
			_args = viewArgs
		} else {
			//teamLog("没有找到模块?")
		}

		function repeatArgs(name) {
			return jsRequires.ViewArgs[name];
		}
		return {
			deps: ['$ocLazyLoad', '$q',
				function($ocLL, $q) {
					var promise = $q.when(1);
					for(var i = 0, len = _args.length; i < len; i++) {
						promise = promiseThen(_args[i]);
					}
					return promise;

					function promiseThen(_arg) {
						if(typeof _arg == 'function')
							return promise.then(_arg);
						else
							return promise.then(function() {
								var nowLoad = requiredData(_arg);
								if(!nowLoad)
									return console.log('找不到文件 [' + _arg + ']');
								return $ocLL.load(nowLoad);
							});
					}

					function requiredData(name) {
						if(jsRequires.modules)
							for(var m in jsRequires.modules)
								if(jsRequires.modules[m].name && jsRequires.modules[m].name === name)
									return jsRequires.modules[m];
						return jsRequires.scripts && jsRequires.scripts[name];
					}
				}
			]
		};
	}
}]);
